<template>
	<view>
		<view class="column-css view-cente">
			<view class="row-css view-cente-cle">
				<view class="view-cente-cle-text">所属承运商</view>
				<view style="position: relative;flex: 1;margin-top: -3rpx;z-index: 999;">
					<input v-model="driverreg.etpName" @input="search" :disabled="isDisabled" placeholder="请输入承运企业全称" />
					<view class="ul">
						<view class="li" v-for="(item, index) in list" :key="index" @click="selectEtp(item)">{{ item.etpName }}</view>
					</view>
				</view>
				<image v-if="!isDisabled" style="width: 38rpx;height: 33rpx;margin-left: 10rpx;" mode="aspectFit" @click="oncard" src="@/static/icon_scan.png"></image>
			</view>
		</view>
		<view class="row-css view-cente view-cente-cle" style="justify-content: space-between;align-items: center;margin: 0 30rpx;">
			<view class="row-css">
				<view class="view-cente-cle-text">当前手机号</view>
				<view>{{ driverreg.captainPhone }}</view>
			</view>
		</view>
		<view class="row-css" style="padding-left: 20rpx;">
			<view class="column-css" style="width: 8rpx;background: #2979ff;margin: 5rpx 10rpx;"></view>
			<view style="font-weight: bold;">请上传本人有效身份证 (必填)</view>
		</view>
		<view class="column-css" style="margin: 0 30rpx;color: #5f6579">
			<!-- <view>上传身份证与驾驶证</view> -->
			<view class="row-css" style="font-size: 24rpx;color: #333333;">
				<view class="column-css" style="padding-top: 25rpx;text-align: center;">
					<image
						style="width: 340rpx;height: 230rpx;"
						mode="aspectFit"
						id="idcardPic1"
						:src="driverreg.idcardPic1 == '' ? modeimage01 : driverreg.idcardPic1"
						@tap="chooseImage(1)"
					></image>
					<view style="padding-top: 15rpx;">身份证人像面</view>
				</view>
				<view class="column-css" style="padding-top: 25rpx;text-align: center;margin-left:20rpx;">
					<image
						style="width: 340rpx;height: 230rpx;"
						mode="aspectFit"
						id="idcardPic2"
						:src="driverreg.idcardPic2 == '' ? modeimage02 : driverreg.idcardPic2"
						@tap="chooseImage(2)"
					></image>
					<view style="padding-top: 15rpx;">身份证国徽面</view>
				</view>
			</view>
		</view>
		<view style="width: 100%; height: 20rpx;background: #F1F1F1;margin: 20rpx 0px;"></view>
		<view style="font-weight: bold;padding-left: 30rpx;">请确定委托收款人信息</view>
		<view class="column-css view-cente">
			<view class="row-css view-cente-cle">
				<view class="view-cente-cle-text">姓名</view>
				<input style="z-index: 1;flex: 1;" 
				v-model="driverreg.captainName" 
				:disabled="driverreg.idcardPic1 && !isDisabled ? false : true"
				:placeholder="driverreg.idcardPic1 ? '证件识别错误，请手动填写' : '请上传身份证,系统自动识别'"
				/>
			</view>
		</view>
		<view class="column-css view-cente">
			<view class="row-css view-cente-cle">
				<view class="view-cente-cle-text">身份证号</view>
				<input
					style="z-index: 1;flex: 1;"
					v-model="driverreg.idcard"
					:disabled="driverreg.idcardPic1 && !isDisabled ? false : true"
					:placeholder="driverreg.idcardPic1 ? '证件识别错误，请手动填写' : '请上传身份证,系统自动识别'"
				/>
			</view>
		</view>
		<view style="width: 100%; height: 20rpx;background: #F1F1F1;margin: 20rpx 0pt;"></view>
		<view class="view-button" @click="shake()">去认证</view>
		<uni-popup ref="popup" type="bottom" mask-background-color="rgba(0,0,0,0.8)">
			<view class="popup-wrap">
				<view class="popup-describe">
					<image v-if="index == 1" src="../../../static/icon_example_idcard01.png" mode="aspectFit"></image>
					<image v-if="index == 2" src="../../../static/icon_example_idcard02.png" mode="aspectFit"></image>
					<view>
						<view class="title">{{title}}</view>
						<view class="desc">
							<view>保证证件四角可见，无遮挡，无反光；</view>
							<view>{{desc}}</view>
						</view>
					</view>
				</view>
				<view class="popup-box">
					<view @click="onCamera(0)">拍照</view>
					<view @click="onCamera(1)">从相册选择</view>
				</view>
				<view class="popup-cancel" @click="onCancel">取消</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import util from '@/common/util.js'
	import throttle from '@/common/helper/throttle.js'
	export default {
		data() {
			return {
				modeimage01: '../../../static/icon_carmer01.png',
				modeimage02: '../../../static/icon_carmer02.png',
				userInfo: {},
				driverreg: {
					etpName: '',
					idcardPic1: '',
					idcardPic2: '',
					captainName: '',
					idcard: ''
				},
				index: '',
				isDisabled: false,
				shipInfo: {},
				list: [],
				disabledEtp: false
			}
		},
		onLoad(options) {
			this.userInfo = uni.getStorageSync(this.DATA_KEY.userInfo);
			this.isDisabled = true
			this.getShipInfo()
			this.driverreg.captainPhone = this.userInfo.captainPhone
			this.getEtpList()
		},
		async onShow() {
			if(uni.getStorageSync(this.DATA_KEY.shipAuthFlag)) {
				await this.savePlatformDriverLive(this.orderNumber);
				uni.setStorageSync(this.DATA_KEY.shipAuthFlag, false);
				uni.navigateBack({
					delta: 1
				});
			}
		},
		methods: {
			chooseImage(index) {
				if (this.isDisabled) return;
				this.index = index;
				this.$refs.popup.open()
				if(this.index == 1) {
					this.title = '请上传身份证人像面照片'
					this.desc = '姓名、身份证号码等信息清晰，无涂改'
				} else if(this.index == 2) {
					this.title = '请上传身份证国徽面照片'
					this.desc = '签发机关、有效期等信息清晰，无涂改'
				}
			},
			onCamera(num) {
				let sourceType
				num === 0 ? sourceType = ['camera'] : sourceType = ['album'] 
				let index = this.index
				this.$refs.popup.close()
				uni.chooseImage({
					count: 1,
					sourceType: sourceType,
					sizeType: 'compressed',
					success: async res => {
						console.log('ddd======1------------>', res.tempFiles);
						console.log('ddd======2------------>', res.tempFiles[0]);
						console.log('ddd======3------------>', res.tempFiles[0].size);
						let resSize = res.tempFiles[0].size;
						if (resSize > 10485760) {
							uni.showToast({
								title: '上传的图片大小不超过10M,请重新上传！',
								icon: 'none',
								duration: 2000,
								mask: true
							});
							return;
						}
						uni.showLoading({
							title: '上传中'
						});
						if (index == 1) {
							const file = res.tempFilePaths[0]
							let uploadRes = await util.upload(file, {
								fileType: '2',
								mobile: this.userInfo.mobile,
								fileId: Math.floor(Math.random() * 1259),
								ocrOrNot: '1',
								orderId: ''
							}, '/driverService/uploadIdcard')
							if (uploadRes) {
								this.driverreg.idcardPic1 = uploadRes.data.imgurl;
								this.idPhotoUp = uploadRes.data.idCardBase64;
								this.driverreg.captainName = uploadRes.data.name;
								this.driverreg.idcard = uploadRes.data.id;
								this.driverreg.driverNameOcrIdcard = uploadRes.data.name;
								this.driverreg.idOcrIdcard = uploadRes.data.id;
								this.driverreg.uploadIdCardFlag = uploadRes.data.uploadIdCardFlag;
								this.driverreg.uploadIdCardMsg = uploadRes.data.uploadIdCardMsg;
							}
							
						} else if (index == 2) {
							const file = res.tempFilePaths[0];
							let uploadRes = await util.upload(file, {
								fileType: '3',
								mobile: this.userInfo.mobile,
								fileId: Math.floor(Math.random() * 1259),
								ocrOrNot: '1',
								orderId: ''
							}, '/driverService/uploadIdcardBack')
							if (uploadRes) {
								this.driverreg.idcardPic2 = uploadRes.data.imgurl;
								this.idPhotoDown = uploadRes.data.idCardBackBase64;
									this.driverreg.idcardValidDate = this.fordata(uploadRes.data.start_date)+ '-' + this.fordata(uploadRes.data.valid_date);
									this.driverreg.idcardStartDate = this.fordata(uploadRes.data.start_date);
									this.driverreg.idcardEndDate = this.fordata(uploadRes.data.valid_date);
									this.driverreg.manualIdcardStartTime = this.fordata(uploadRes.data.start_date);
									this.driverreg.manualIdcardEndTime = this.fordata(uploadRes.data.valid_date);
								this.driverreg.uploadIdCardBackFlag = uploadRes.data.uploadIdCardBackFlag;
								this.driverreg.uploadIdCardBackMsg = uploadRes.data.uploadIdCardBackMsg;
							}
						}
					}
				})
			},
			oncard() {
				if (this.isDisabled) return;
				let that = this;
				uni.scanCode({
					scanType: ['qrCode'],
					success: function(res) {
						console.log('条码：' + JSON.stringify(res));
						that.driverreg.etpId = res.result.split('=')[2].split('&')[0];
						that.driverreg.etpName = res.result.split('=')[3].split('&')[0];
						that.etpName = res.result.split('=')[3].split('&')[0];
						if (res.result.split('=').length > 4) {
							that.driverreg.exemptCode = res.result.split('=')[4];
						}
						// that.wxRequest({
						// 	url: `${that.API}/driverService/checkInvitationCode`,
						// 	method: 'POST',
						// 	data: {
						// 		driverId: uni.getStorageSync(that.DATA_KEY.userInfo).driverId,
						// 		etpId: that.driverreg.etpId,
						// 		exemptCode: that.driverreg.exemptCode
						// 	},
						// 	success: res => {}
						// });
					}
				});
			},
			shake() {
				let that = this
				if (
					!this.driverreg.etpName ||
					!this.driverreg.captainName ||
					!this.driverreg.idcard ||
					!this.driverreg.idcardPic1 ||
					!this.driverreg.idcardPic2
				) {
					uni.showToast({
						title: '请填写完整信息再进行认证',
						icon: 'none'
					})
					return
				}
				uni.showModal({
					title: '认证提示',
					// #ifdef APP-PLUS
					content: '是否去进行实名认证?跳转进行实名认证后需要重新打开当前APP!',
					// #endif
					// #ifdef MP-WEIXIN
					content: '是否去进行实名认证?',
					// #endif
					success: function(res) {
						if (res.confirm) {
							that.goAuth()
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
				return
				that.wxRequest({
					url: `${that.API}/driverService/checkIdCardUnique`,
					method: 'POST',
					title: '校验中...',
					data: {
						driverId: uni.getStorageSync(that.DATA_KEY.userInfo).driverId,
						idcard: that.driverreg.idcard
					},
					success: res => {
						if (res.data.data.status == 0) {
							this.submit()
						} else {
							uni.showModal({
								title: '提示',
								content: res.data.data.message,
								showCancel:false,
								confirmText: '确认',
								success: function(res) {
								}
							});
						}
					}
				});
			},
			submit() {
				let that = this
				
				that.wxRequest({
					url: `${that.API}/driverService/driverRegister`,
					method: 'POST',
					data: that.driverreg,
					title: '提交中...',
					success: res => {
						if (res.data.code == 0) {
							that.goAuth()
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
						
					}
				});
			},
			async goAuth() {
				const result = await this.getDriverIdCardInfo();
				this.accessToken = result.data.accessToken;
				const result2 = await this.getFaceQRCode(result.data);
				let orderNumber = result2.data.orderNumber;
				this.orderNumber = orderNumber;
				// const result3 = await this.savePlatformDriverLive(orderNumber)
				let that = this
				// #ifdef APP-PLUS
				plus.share.getServices(
					function(res) {
						uni.setStorageSync(that.DATA_KEY.shipAuthFlag, true);
						var sweixin = null;
						console.log(res);
						for (var i = 0; i < res.length; i++) {
							var t = res[i];
							console.log(t);
							if (t.id == 'weixin') {
								sweixin = t;
							}
						}
						if (sweixin) {
							console.log('dddd=', 'a=' + sweixin + '=b');
							sweixin.launchMiniProgram({
								// id: 'gh_cec8224b00da',
								id: 'gh_45eec401ff1c',
								type: 0, //0-正式版 1.测试版，2，体验版
								path: 'pages/verify/info/index?id=' + orderNumber
							});
						}
					},
					function(res) {
						console.log(JSON.stringify(res));
					}
				);
				// #endif
				
				// #ifdef MP-WEIXIN
				uni.navigateToMiniProgram({
					// appId: 'wxfd2861dc1c86b3a0',
					appId: 'wxfc1e27e05fdd062b',
					path: 'pages/verify/info/index?id=' + orderNumber,
					envVersion: 'release',
					success(res) {
						uni.setStorageSync(that.DATA_KEY.shipAuthFlag, true);
						console.log('跳转成功');
					},
					fail(res) {
						console.log('跳转失败' + JSON.stringify(res));
					}
				});
				// #endif
			},
			getDriverIdCardInfo() {
				return new Promise((resolve, reject) => {
					let that = this;
					that.wxRequest({
						url: `${that.API}/captainApp/getCaptainIdCardInfo`,
						method: 'GET',
						title: '加载中...',
						success: res => {
							resolve(res.data)
						},
						fail: err => {
							reject(err)
						}
					});
				})
			},
			getFaceQRCode(data) {
				return new Promise((resolve, reject) => {
					let that = this;
					that.wxRequestData({
						url: `${that.API2}/api/face/getFaceQRCode?access_token=` + data.accessToken,
						method: 'POST',
						data: {
							companyTaxNumber: data.taxNumber,
							realName: data.CaptainName,
							idCard: data.idcard,
							idPhotoUp: data.idcard1Base64,
							idPhotoDown: data.idcard2Base64,
							callbackUrl: `${that.API}/driverService/isLivingBodyState`
						},
						success: res => {
							resolve(res.data)
						},
						fail: err => {
							reject(err)
						}
					})
				})
			},
			savePlatformDriverLive(orderNumber) {
				return new Promise((resolve, reject) => {
					let that = this;
					that.wxRequest({
						url: `${that.API}/captainApp/savePlatformDriverLive`,
						method: 'POST',
						data: {
							captainId: that.userInfo.captainId, //船长id
							orderNumber: orderNumber, //活体编号
							accessToken: that.accessToken
						},
						success: res => {
							resolve(res.data)
						},
						fail: err => {
							reject(err)
						}
					})
				})
			},
			onCancel() {
				this.$refs['popup'].close()
			},
			getEtpList() {
				this.wxRequest({
					url: `${this.API}/captainApp/captainEnterprise?etpName=`,
					method: 'GET',
					success: res => {
						this.items = res.data.data;
					}
				})
			},
			search(e) {
				let val = e.detail.value.trim();
				let {
					items
				} = this;
				let arr = [];
				for (let i = 0; i < items.length; i++) {
					if (items[i].etpName.indexOf(val) !== -1) {
						arr.push(items[i]);
					}
				}
				if (!val) {
					this.list = [];
				} else {
					this.list = arr;
				}
			},
			selectEtp(item) {
				this.driverreg.etpId = item.etpId;
				this.driverreg.etpName = item.etpName;
				this.list = [];
			},
			getShipInfo() {
				this.wxRequest({
					url: `${this.API}/captainApp/captainAuthentication?etpId=${uni.getStorageSync(this.DATA_KEY.etpId)}`,
					method: 'GET',
					success: res => {
						if (res.data.code == 0) {
							this.shipInfo = res.data.data
							
							let {
								// etpName,
								// etpId,
								captainPhone,
								idcardPic1,
								idcardPic2,
								captainName,
								idcard
							} = this.shipInfo.captain
							
							this.driverreg = {
								// etpName,
								// etpId,
								captainPhone,
								idcardPic1,
								idcardPic2,
								captainName,
								idcard
							}
							this.driverreg.etpId = uni.getStorageSync(this.DATA_KEY.etpId)
							this.driverreg.etpName = uni.getStorageSync(this.DATA_KEY.etpName)
							if (res.data.data.shippingPayInfoStatus == '1') {
								this.disabledEtp = true
							}
						}
					}
				});
			}
		},
		onUnload() {
			uni.setStorageSync(this.DATA_KEY.shipAuthFlag, false)
		}
	}
</script>

<style lang="scss">
	.popup-wrap{
		// padding: 0 24rpx calc(24rpx + env(safe-area-inset-bottom));
		padding: 0 24rpx calc(24rpx);
		color: #007aff;
		text-align: center;
		background: transparent;
		.popup-describe{
			color: #fff;
			position: absolute;
			top: -55vh;
			left: 50%;
			transform: translate(-50%, 0);
			.title{
				margin: 24rpx 0;
				font-size: 36rpx;
			}
			.desc{
				font-size: 24rpx;
			}
		}
		.popup-box{
			background: #fff;
			margin-bottom: 24rpx;
			border-radius: 8rpx;
			view{
				padding: 24rpx 0;
				&:first-child{
					border-bottom: 1rpx solid #f9f9f9;
				}
			}
		}
		.popup-cancel{
			background: #fff;
			padding: 24rpx 0;
			border-radius: 8rpx;
		}
	}
page {
	background: #ffffff;
}
.desc-css{
	font-size: 24rpx;
	color: #4175F7;
	padding: 0 30rpx;
}
.row-css {
	display: flex;
	flex-direction: row;
}

.column-css {
	display: flex;
	flex-direction: column;
}
.view-cente {
	background: #ffffff;
	padding: 0 30rpx;
}
.view-cente-cle {
	padding: 25rpx 0;
	border-bottom: 1rpx solid #eeeeee;
}
.view-cente-cle-text {
	width: 180rpx;
	color: #5f6579;
}
.code-view {
	display: flex;
	width: 230rpx;
	font-size: 28rpx;
	color: #ffffff;
	background: #2979ff;
	justify-content: center;
	align-items: center;
	border: 1rpx solid #2979ff;
	padding: 15rpx 0;
}
.view-button {
	display: flex;
	flex: 1;
	background: #2b7cff;
	border-radius: 5rpx;
	padding: 20rpx;
	margin: 30rpx;
	/* margin-top: 50rpx; */
	justify-content: center;
	color: #ffffff;
}
.ul {
	position: absolute;
	margin-top: 30rpx;
	left: 0;
	top: 100%;
	width: 100%;
	background: #ffffff;
}
.li {
	border-bottom: 1rpx solid #eeeeee;
	padding: 25rpx 20rpx;
}
</style>
